/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import dao.util.HibernateUtil;
import java.util.ArrayList;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.CriteriaQuery;
import org.hibernate.criterion.Criterion;
import org.hibernate.engine.TypedValue;
import pojo.Binhluan;
import pojo.Dienthoai;
import pojo.Taikhoan;
import template.choosePage;

/**
 *
 * @author vinh
 */
public class BinhLuanDAO extends AbstractDAO<Binhluan, Integer>{

    @Override
    protected Class getPoJoclass() {       
      return Binhluan.class;
    }
    
    public ArrayList<Binhluan>  getBinhLuan( int Madienthoai)// lay binh luan theo ma dien thoai
    {
        ArrayList<Binhluan> danhsachbinhluan;
        Session session = HibernateUtil.getSessionFactory().openSession();
        String hql = String.format("select obj from %s obj where obj.dienthoai.madienthoai = '%d'", Binhluan.class.getName(), Madienthoai);

        Query query = session.createQuery(hql);
        danhsachbinhluan = (ArrayList<Binhluan>) query.list();
        session.close();
        return danhsachbinhluan;
    }
    
    public void  addBinhLuan( int Madienthoai, String loibinhluan, String tendangnhap)// them binh luan = ma dien thoai, loi binh luan, ten dang nhap
    {
        Binhluan bl = new Binhluan();
        
        Dienthoai dt = new Dienthoai();
        DienThoaiDAO dtdao = new DienThoaiDAO();
        dt = dtdao.get(Madienthoai);
        
        Taikhoan tk = new Taikhoan();
        TaiKhoanDAO tkdao = new TaiKhoanDAO();
        tk = tkdao.getTaiKhoanByUsername(tendangnhap);
        
        bl.setBinhluan(loibinhluan);//////// xem lại
        bl.setDienthoai(dt);/// xem lại
        bl.setTaikhoan(tk);/////
        
        
        
        Binhluan tam = new Binhluan();
        bl.setStt(getAllbinhluan()+1);///// xem lại

        
        
        
        Session session = HibernateUtil.getSessionFactory().openSession();
        org.hibernate.Transaction  tx = session.beginTransaction();
        session.save(bl);
        tx.commit();
        session.flush();
        session.close();
    }
    
    public int getAllbinhluan()
    {
        ArrayList<Binhluan> danhsachbinhluan;
        Session session = HibernateUtil.getSessionFactory().openSession();
        String hql = String.format("select obj from %s obj", Binhluan.class.getName());
        Query query = session.createQuery(hql);
        danhsachbinhluan = (ArrayList<Binhluan>) query.list();
        session.close();
        return danhsachbinhluan.size();

    }
    
}
